#include "../ged/typedefs.hpp"
#include "Command.hpp"
#include "Editor.hpp"
#include "Image.hpp"
#include "Observer.hpp"

namespace ged {

Editor* Editor::instance = 0L;

Editor::Editor()
	: command_count_(0), observer_(0L)
{
}

Editor::Editor(const Editor& e)
{
}

Editor::~Editor()
{
}

Editor* Editor::getInstance()
{
	if (!instance)
		instance = new Editor;
	return instance;
}

void Editor::execute(PCommand c)
{
	if (!image_) {
		throw NoImageException();
	}

	c->execute(image_);
	while (command_count_ != com_.size()) {
		com_.pop_back();
	}
	com_.push_back(c);
	command_count_++;
	notify();
}

void Editor::unExecute()
{
	if (command_count_ > 0) {
		com_[command_count_-1]->unExecute(image_);
		--command_count_;
		notify();
	}
}

void Editor::redo()
{
	if (command_count_ < com_.size() && command_count_ >= 0) {
		com_[++command_count_-1]->execute(image_);
		notify();
	}
}

void Editor::addImageLayer(const PGILImage& image)
{
	// Późne tworzenie obrazka, kiedy już znamy minimalne wymiary
	if (!image_) {
		image_ = PImage(new Image(image->dimensions()));
	}

	image_->addLayer(image);
	notify();
}

void Editor::setObserver(const PObserver& observer)
{
	observer_ = observer;
}

void Editor::notify() const
{
	if (observer_)
		observer_->update();
}

const PImage Editor::getImage() const
{
	if (!image_  ) {
		throw NoImageException();
	}

	return image_;
}

} // namespace ged
